package com.njupt.sellsec.controller;

import com.njupt.sellsec.exception.SellerAuthorizeException;
import com.njupt.sellsec.vo.OrderDetailVO;
import com.njupt.sellsec.domain.OrderInfo;
import com.njupt.sellsec.domain.SellUser;
import com.njupt.sellsec.result.CodeMsg;
import com.njupt.sellsec.result.Result;
import com.njupt.sellsec.service.GoodsService;
import com.njupt.sellsec.service.Impl.SellUserServiceImpl;
import com.njupt.sellsec.service.OrderInfoService;
import com.njupt.sellsec.service.SellUserService;
import com.njupt.sellsec.vo.GoodsFormVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 15:36 2018/7/31
 * @Modified By:
 **/
@RequestMapping("/order")
@Controller
public class SecOrderController {
    @Autowired
    private SellUserService sellUserService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private GoodsService goodsService;

    @RequestMapping("/detail")
    @ResponseBody
    public Result<OrderDetailVO> orderDetail(Model model,
                                             HttpServletResponse response,
                                             @CookieValue(value = SellUserServiceImpl.COOKIE_NAME_TOKEN,required = false)String cookieValue,
                                             @RequestParam(value = SellUserServiceImpl.COOKIE_NAME_TOKEN,required = false)String paramToken,
                                             @RequestParam("orderId")long orderId) throws IOException {

        if (StringUtils.isEmpty(cookieValue)&& StringUtils.isEmpty(paramToken)){


            throw new SellerAuthorizeException();
        }
        String token = StringUtils.isEmpty(paramToken)?cookieValue:paramToken;
        SellUser user = sellUserService.findUserByToken(response,token);
        model.addAttribute("user",user);

        OrderInfo orderInfo = orderInfoService.getOrderInfoByOrderId(orderId);

        if (orderInfo==null){
            return Result.error(CodeMsg.ORDER_NOT_EXITS.getMsg());
        }
        GoodsFormVO goods = goodsService.getGoodInfoById(orderInfo.getGoodsId());
        OrderDetailVO orderDetailVO = new OrderDetailVO();
        orderDetailVO.setGoodsFormVO(goods);
        orderDetailVO.setOrderInfo(orderInfo);

        return Result.success(orderDetailVO);

    }
}
